﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DAL;
using Model;
using SqlSugar;

namespace BLL
{
    public static class CustomerMainService
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public static string insertCustomerMain(CustomerMain customerMain)
        {
            try
            {
                Guid id = Guid.NewGuid();
                customerMain.Id = id;
                if (customerMain.customerContractList != null && customerMain.customerContractList.Count > 0)
                {
                    foreach (var item in customerMain.customerContractList)
                    {
                        item.CustomerMainId = id;
                    }
                }

                if (customerMain.customerDeliverList != null && customerMain.customerDeliverList.Count > 0)
                {
                    foreach (var item in customerMain.customerDeliverList)
                    {
                        item.CustomerMainId = id;
                    }
                }
                if (customerMain.customerFinanceList != null && customerMain.customerFinanceList.Count > 0)
                {
                    foreach (var item in customerMain.customerFinanceList)
                    {
                        item.CustomerMainId = id;
                    }
                }
                
                SqlSugarHelp.scope.Ado.BeginTran();
               var x = SqlSugarHelp.scope.Storageable(customerMain)
                                    .SplitError(i => i.Any(it => it.CustomerCode == i.Item.CustomerCode), "客户编号已经存在已存在")//编辑验证
                                    .SplitInsert(i => true)//其余插入
                                    .WhereColumns(it => it.CustomerCode)//将Name取代主键作为条件 （多字段it=>new{it.x1,it.x2}）
                                    .ToStorage();
                if (x.ErrorList.Any())//输出所有错误部分
                {
                    foreach (var item in x.ErrorList)
                    {
                        Logger.Error(item.StorageMessage+"[客户编号："+customerMain.CustomerCode +"；客户名称："+customerMain.CustomerName +"]");
                        MessageBox.Show(item.StorageMessage + "[客户编号：" + customerMain.CustomerCode + "；客户名称：" + customerMain.CustomerName + "]");
                        return "0";
                    }
                }
                int r =   x.AsInsertable.ExecuteCommand();
                int r1  =SqlSugarHelp.scope.Insertable(customerMain.customerContractList).ExecuteCommand();
                int r2 = SqlSugarHelp.scope.Insertable(customerMain.customerDeliverList).ExecuteCommand();
                int r3 = SqlSugarHelp.scope.Insertable(customerMain.customerFinanceList).ExecuteCommand();
                SqlSugarHelp.scope.Ado.CommitTran();
                return "1";
            }
            catch (Exception e)
            {
                SqlSugarHelp.scope.Ado.RollbackTran();
                return e.Message;
            }
            return "0";
        }

        /// <summary>
        /// 查询所有不在 潜在 公共 黑名单 待审核的客户
        /// </summary>
        /// <returns></returns>
        public static List<CustomerMain> getNoApproachCustomer()
        {
            return SqlSugarHelp.scope.Queryable<CustomerMain>().Where(it =>
                                        SqlFunc.Subqueryable<CustomerPotential>().Where(s => s.CustomerMainId == it.Id).NotAny()
                                        && SqlFunc.Subqueryable<CustomerBlack>().Where(black => black.CustomerMainId == it.Id).NotAny()
                                        && SqlFunc.Subqueryable<CustomerPublic>().Where(pub => pub.CustomerMainId == it.Id).NotAny())
                                        .OrderBy(it => it.CustomerLevel)
                                        .Mapper(it => it.customerContractList, it => it.customerContractList.First().CustomerMainId)
                                                                .Mapper(it => it.customerDeliverList, it => it.customerDeliverList.First().CustomerMainId)
                                                                .Mapper(it => it.customerFinanceList, it => it.customerFinanceList.First().CustomerMainId)
                                        .ToList();
        }

        public static int customerToPublic(List<CustomerPublic> customerPublicList)
        {
            return SqlSugarHelp.scope.Insertable(customerPublicList).ExecuteCommand();
        }

        /// <summary>
        /// 查询未分配且不是黑名单的公共池客户
        /// </summary>
        /// <returns></returns>
        public static List<CustomerMain> getAllCustomerMainNotInPotentialAndBlack()
        {
            return SqlSugarHelp.scope.Queryable<CustomerMain>().Where(it =>
                                        SqlFunc.Subqueryable<CustomerPotential>().Where(s => s.CustomerMainId == it.Id).NotAny()
                                        && SqlFunc.Subqueryable<CustomerBlack>().Where(black => black.CustomerMainId == it.Id).NotAny()
                                        && SqlFunc.Subqueryable<CustomerPublic>().Where(pub => pub.CustomerMainId == it.Id).Any())
                                        .OrderBy(it => it.CustomerLevel)
                                        .ToList();
        }

        /// <summary>
        /// 查询潜在客户
        /// </summary>
        /// <returns></returns>
        public static List<CustomerMain> getAllCustomerMainNotInPotentialAndBlack(Guid salesManId)
        {
            return SqlSugarHelp.scope.Queryable<CustomerMain>()
                                     .InnerJoin<CustomerPotential>((m,p)=> m.Id == p.CustomerMainId)
                                     .InnerJoin<PotentialSalesman>((m,p,s) => p.Id == s.PotentialId)
                                     .Where((m,p,s) => s.SalesManId == salesManId)
                                     .Select(m => m)
                                        .ToList();
        }

        public static List<CustomerMain> getAllCustomerMain()
        {
            return SqlSugarHelp.scope.Queryable<CustomerMain>().Mapper(it => it.customerContractList,it => it.customerContractList.First().CustomerMainId)
                                                                .Mapper(it => it.customerDeliverList,it => it.customerDeliverList.First().CustomerMainId)
                                                                .Mapper(it => it.customerFinanceList,it => it.customerFinanceList.First().CustomerMainId).ToList();
        }

        public static int updateCustomerMain(CustomerMain customerMain)
        {
            int i = 0;
            try
            {
                SqlSugarHelp.scope.Ado.BeginTran();
               i += SqlSugarHelp.scope.Updateable(customerMain).ExecuteCommand();
               var x = SqlSugarHelp.scope.Storageable(customerMain.customerContractList).ToStorage();
                x.AsInsertable.ExecuteCommand(); //执行插入
                x.AsUpdateable.ExecuteCommand(); //执行更新　
                var x1 = SqlSugarHelp.scope.Storageable(customerMain.customerDeliverList).ToStorage();
                x1.AsInsertable.ExecuteCommand(); //执行插入
                x1.AsUpdateable.ExecuteCommand(); //执行更新　
                var x2 = SqlSugarHelp.scope.Storageable(customerMain.customerFinanceList).ToStorage();
                x2.AsInsertable.ExecuteCommand(); //执行插入
                x2.AsUpdateable.ExecuteCommand(); //执行更新　
                i = 1;
                SqlSugarHelp.scope.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelp.scope.Ado.RollbackTran();
                MessageBox.Show(ex.Message);
            }
            return i;
        }

        public static int deleteCustomerMain(CustomerMain customerMain)
        {
            int i = 0;
            try
            {
                SqlSugarHelp.scope.Ado.BeginTran();
                i += SqlSugarHelp.scope.Deleteable<CustomerContract>(customerMain.customerContractList).ExecuteCommand();
                i += SqlSugarHelp.scope.Deleteable<CustomerDeliver>(customerMain.customerDeliverList).ExecuteCommand();
                i += SqlSugarHelp.scope.Deleteable<CustomerFinance>(customerMain.customerFinanceList).ExecuteCommand();
                i += SqlSugarHelp.scope.Deleteable<CustomerMain>(customerMain).ExecuteCommand();
                SqlSugarHelp.scope.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelp.scope.Ado.RollbackTran();
                MessageBox.Show(ex.Message);
            }
            return i;
        }

        public static CustomerMain CheckCustomerMainAlreadyExists(string customerCode, string customerName)
        {
            return SqlSugarHelp.scope.Queryable<CustomerMain>().Mapper(it => it.customerContractList, it => it.customerContractList.First().CustomerMainId)
                                                                .Mapper(it => it.customerDeliverList, it => it.customerDeliverList.First().CustomerMainId)
                                                                .Mapper(it => it.customerFinanceList, it => it.customerFinanceList.First().CustomerMainId)
                                                                .First(it => it.CustomerCode.Contains(customerCode));
        }

        public static int transferCustomerMainToPotential(List<CustomerPotential> customerPotentialList, List<PotentialSalesman> potentialSalesmanList)
        {
            int i = 0;
            try
            {
                SqlSugarHelp.scope.Ado.BeginTran();
                SqlSugarHelp.scope.Insertable(customerPotentialList).ExecuteCommand();
                SqlSugarHelp.scope.Insertable(potentialSalesmanList).ExecuteCommand();
                SqlSugarHelp.scope.Ado.CommitTran();
                i = 1;
            }
            catch (Exception e)
            {
                SqlSugarHelp.scope.Ado.RollbackTran();
                MessageBox.Show(e.Message);
            }
            return i;
        }
    }
}
